
module MetaUI where
import System.Time
import MetaMongo
import Database.MongoDB
import FlsParser
import Control.OldException
import System.IO
import Data.Maybe (fromJust)
import qualified Data.ByteString.Lazy.Char8 as L
-- startIO here as well
startDB :: [BodyLine] -> IO ()
startDB bls =
    do pipe <- runIOE $ connect (host "127.0.0.1")
       --doClearDB pipe
       --doLoadBodyFile pipe bls
       print "BodyFile loaded!!"
       --doTimelineSetup pipe
       print "Timeline file setup"
       print "starting to calculate distributions"
       --doCalcDistribution pipe
       print "distributions complete"
       print "Ready for Input:"
       getInput pipe

loadFile name = do bodyfile <- getFile name
                   testMongo (getBLines bodyfile)

testMongo bodyfile = do startDB bodyfile

getBLines bodyfile = fromJust (maybeParseB bodyfile)

getFile addr =
  do fh <- openFile addr ReadMode
     contents <- L.hGetContents fh
     return contents

getInput pipe
  = do line <- getLine
       if(line == [])
	 then (getInput pipe)
         else if (isQuit line)
                then return ()
	        else (do handle (\_ -> return ()) (processLine pipe line)
		         getInput pipe)
	

processLine pipe line =
    do info <- getInfo line
       cmd <- getCMD line
       case cmd of
	     "tlc" -> performTLC pipe info -- complete timeline
	     "tlr" -> performTLR pipe info -- takes seconds
	     "distrcmp" -> performDCMP pipe info --takes int, and grabs name auto
	     "ledCorr" -> performLEDCorr pipe info -- takes int, and grabs name auto
	     "tsCorr" -> performTSCorr pipe info --takes int grabs name
	     "sed" -> performSED pipe info -- takes int, grabs name... could make it take reg name
	     "getname" -> performGN info
	     "tsdir" -> performTSDIR pipe info
	     "eddir" -> performEDDIR pipe info
	     _ -> performERROR
    where
      getCMD line = do return (head (words line))
      getInfo line = do return (unwords (tail (words line)))


performGN xs = do name <- (grabName (Prelude.read xs :: Int))
                  print name

grabName lineNum =
    do fh <- openFile "testData/Initial" ReadMode
       str <- hGetContents fh
       let result = Prelude.takeWhile (/= '"') ((Prelude.drop 45 ((lines str) !! lineNum)))
       --hClose fh
       return result

performEDDIR pipe xs =
    do before <- getMilSec
       if (xs ==[])
           then do response <- fnfError
                   after <- getMilSec
                   putMSG response before after
           else do name <- grabName (Prelude.read ((words xs)!!0) :: Int)
                   name2 <- grabName (Prelude.read ((words xs)!!1) :: Int)
                   fh <- openFile "testData/edDir" WriteMode
                   doEditDistanceCorrDir name name2 pipe fh
                   after <- getMilSec
                   putMSG "EditDistanceCorrDir complete" before after
                   hClose fh

performTSDIR pipe xs =
    do  before <- getMilSec
        if (xs == [])
            then do response <- fnfError
                    after <- getMilSec
                    putMSG response before after
            else do name <- grabName (Prelude.read ((words xs)!!0) :: Int)
                    name2 <- grabName (Prelude.read ((words xs)!!1) :: Int)
                    fh <- openFile "testData/tsDir" WriteMode
                    doTimeStampCorrDir name name2 pipe fh
                    after <- getMilSec
                    putMSG "TimestampCorrDir complete" before after
                    hClose fh

performSED pipe xs =
    do before <- getMilSec
       if (xs == [])
            then do response <- fnfError
                    after <- getMilSec
                    putMSG response before after
            else do name <- grabName (Prelude.read xs :: Int)
                    fh <- openFile "testData/simpleEditDistance" WriteMode
                    doSimpleEditDistance name pipe fh
                    after <- getMilSec
                    putMSG "SimpleEditDistance complete" before after
                    hClose fh

performTSCorr pipe xs =
    do before <- getMilSec
       if (xs == [])
            then do response <- fnfError
                    after <- getMilSec
                    putMSG response before after
            else do name <- grabName (Prelude.read xs :: Int)
                    fh <- openFile "testData/TSCorr" WriteMode
                    doTimestampCorr name pipe fh
                    after <- getMilSec
                    putMSG ("TSCorr complete") before after
                    hClose fh

performLEDCorr pipe xs =
    do before <- getMilSec
       if (xs == [])
            then do response <- fnfError
                    after <- getMilSec
                    putMSG response before after
            else do name <- grabName (Prelude.read xs :: Int)
                    fh <- openFile "testData/LEDCorr" WriteMode
                    doEditDistance name pipe fh
                    after <- getMilSec
                    putMSG ("EditDistance Complete" ++ name) before after
                    hClose fh

performDCMP pipe xs =
    do before <- getMilSec
       if (xs == [])
            then do response <- fnfError
                    after <- getMilSec
                    putMSG response before after
            else do name <- grabName (Prelude.read xs :: Int)
                    fh <- openFile "testData/cmpDistr" WriteMode
                    doCmpDistr name pipe fh
                    after <- getMilSec
                    putMSG ("DistributionCmp Complete" ++ name) before after
                    hClose fh

performTLC pipe xs =
    do before <- getMilSec
       if (xs == [])
            then do response <- fnfError
                    after <- getMilSec
                    putMSG response before after
            else do fh <- openFile "testData/completeTimeline" WriteMode
                    (doCompleteTimeline pipe fh)
                    after <- getMilSec
                    putMSG "TLC-Complete" before after
                    hClose fh

performTLR pipe xs =
    do before <- getMilSec
       if (xs == [])
            then do response <- fnfError
                    after <- getMilSec
                    putMSG response before after
            else do fh <- openFile "testData/timelineRange" WriteMode
                    (doTimelineRange seconds pipe fh)
                    after <- getMilSec
                    putMSG "TLR-Complete" before after
                    hClose fh
        where
            seconds = Prelude.read xs :: Integer

metaError :: Exception -> IO String
metaError e = return "Monkeys have destroyed the MetaDateServer\nTry again later they will rebuild it"

fnfError :: IO String
fnfError = return "File Not Found"

putMSG :: String -> Integer -> Integer -> IO()
putMSG response before after = putStrLn (response ++ "\nTime: " ++ show (subtract before after) ++ " ms")

performERROR :: IO()
performERROR = print "Enter Valid command"

getMilSec :: IO Integer
getMilSec = do
              sec <- getClockTime >>=(\(TOD sec _) -> return sec)
              psec <- getClockTime >>=(\(TOD _ psec) -> return psec)
              return (sec * 1000 + (div psec 1000000000))

isQuit xs = "quit" == take 5 xs
